<template>
  <DashboardLayout
    title="美食网管理后台"
    logo-icon="🍜"
    username="超级管理员"
    user-type="admin"
    :active-menu="activeMenu"
    :current-title="getCurrentTitle()"
    breadcrumb-home="管理后台"
    @menu-select="handleMenuSelect"
    @logout="handleLogout"
  >
    <template #menu>
      <el-menu-item index="overview">
        <el-icon><DataAnalysis /></el-icon>
        <span>系统概览</span>
      </el-menu-item>
      <el-menu-item index="users">
        <el-icon><User /></el-icon>
        <span>用户管理</span>
      </el-menu-item>
      <el-menu-item index="merchants">
        <el-icon><Shop /></el-icon>
        <span>商家管理</span>
      </el-menu-item>
      <el-menu-item index="categories">
        <el-icon><Grid /></el-icon>
        <span>分类管理</span>
      </el-menu-item>
    </template>

    <template #content>
      <!-- 系统概览 -->
      <div v-if="activeMenu === 'overview'" class="content-section">
        <div class="section-header">
          <h2>系统概览</h2>
          <p>平台运营数据总览</p>
        </div>
        
        <div class="stats-grid">
          <el-card class="stat-card users">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <h3>总用户数</h3>
                <p class="stat-number">{{ stats.totalUsers }}</p>
                <span class="stat-trend">+12.5% 较上月</span>
              </div>
            </div>
          </el-card>
          
          <el-card class="stat-card merchants">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Shop /></el-icon>
              </div>
              <div class="stat-info">
                <h3>总商家数</h3>
                <p class="stat-number">{{ stats.totalMerchants }}</p>
                <span class="stat-trend">+8.3% 较上月</span>
              </div>
            </div>
          </el-card>
          
          <el-card class="stat-card foods">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Food /></el-icon>
              </div>
              <div class="stat-info">
                <h3>总美食数</h3>
                <p class="stat-number">{{ stats.totalFoods }}</p>
                <span class="stat-trend">+15.6% 较上月</span>
              </div>
            </div>
          </el-card>

          <el-card class="stat-card pending">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <h3>待审核</h3>
                <p class="stat-number">{{ pendingMerchants }}</p>
                <span class="stat-trend">需要处理</span>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 快速操作 -->
        <div class="quick-actions">
          <h3>快速操作</h3>
          <div class="action-grid">
            <el-card class="action-card" @click="activeMenu = 'merchants'" shadow="hover">
              <div class="action-content">
                <el-icon class="action-icon"><Shop /></el-icon>
                <span class="action-text">商家审核</span>
                <el-badge v-if="pendingMerchants > 0" :value="pendingMerchants" class="action-badge" />
              </div>
            </el-card>
            <el-card class="action-card" @click="activeMenu = 'users'" shadow="hover">
              <div class="action-content">
                <el-icon class="action-icon"><User /></el-icon>
                <span class="action-text">用户管理</span>
              </div>
            </el-card>
            <el-card class="action-card" @click="activeMenu = 'categories'" shadow="hover">
              <div class="action-content">
                <el-icon class="action-icon"><Grid /></el-icon>
                <span class="action-text">分类管理</span>
              </div>
            </el-card>
          </div>
        </div>
      </div>
      
      <!-- 用户管理 -->
      <div v-if="activeMenu === 'users'" class="content-section">
        <div class="section-header">
          <h2>用户管理</h2>
          <div class="section-actions">
            <el-input
              v-model="userSearch"
              placeholder="搜索用户名..."
              prefix-icon="Search"
              style="width: 250px; margin-right: 12px;"
              clearable
              @input="handleUserSearch"
            />
            <el-button type="primary" @click="showAddUserDialog">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
            <el-button type="danger" @click="batchDeleteUsers" :disabled="selectedUsers.length === 0">
              批量删除 ({{ selectedUsers.length }})
            </el-button>
            <el-button type="info" @click="refreshUsers">刷新</el-button>
          </div>
        </div>
        
        <div class="table-container">
          <el-table 
            :data="users" 
            v-loading="loading"
            @selection-change="handleUserSelectionChange"
            stripe
            class="admin-table"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="userId" label="ID" width="80" />
            <el-table-column prop="username" label="用户名" min-width="120" show-overflow-tooltip />
            <el-table-column prop="avatarPath" label="头像" width="80" align="center">
              <template #default="scope">
                <el-avatar :size="40" src="/toux.png" />
              </template>
            </el-table-column>
            <el-table-column prop="registerTime" label="注册时间" min-width="160">
              <template #default="scope">
                {{ formatDate(scope.row.registerTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="lastLoginTime" label="最后登录" min-width="160">
              <template #default="scope">
                {{ formatDate(scope.row.lastLoginTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="320" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewUser(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="editUser(scope.row)">编辑</el-button>
                <el-button size="small" type="warning" @click="resetUserPassword(scope.row)">重置密码</el-button>
                <el-button size="small" type="danger" @click="deleteUser(scope.row.userId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <CustomPagination
            v-model:current-page="userPagination.page"
            v-model:page-size="userPagination.size"
            :total="userPagination.total"
            :page-sizes="[20, 50, 100]"
            @size-change="handleUserPageSizeChange"
            @current-change="handleUserPageChange"
          />
        </div>
      </div>
      
      <!-- 商家管理 -->
      <div v-if="activeMenu === 'merchants'" class="content-section">
        <div class="section-header">
          <h2>商家管理</h2>
          <div class="section-actions">
            <el-input
              v-model="merchantSearch"
              placeholder="搜索商家名称..."
              prefix-icon="Search"
              style="width: 250px; margin-right: 12px;"
              clearable
              @input="handleMerchantSearch"
            />
            <el-select v-model="merchantFilter" placeholder="筛选状态" style="width: 120px; margin-right: 12px;" @change="handleMerchantFilterChange">
              <el-option label="全部" value="" />
              <el-option label="待审核" :value="0" />
              <el-option label="已通过" :value="1" />
              <el-option label="已拒绝" :value="2" />
            </el-select>
            <el-button type="primary" @click="showAddMerchantDialog">
              <el-icon><Plus /></el-icon>
              添加商家
            </el-button>
            <el-button type="success" @click="batchApproveMerchants(1)" :disabled="selectedMerchants.length === 0">
              批量通过 ({{ selectedMerchants.length }})
            </el-button>
            <el-button type="warning" @click="batchApproveMerchants(2)" :disabled="selectedMerchants.length === 0">
              批量拒绝 ({{ selectedMerchants.length }})
            </el-button>
            <el-button type="danger" @click="batchDeleteMerchants" :disabled="selectedMerchants.length === 0">
              批量删除 ({{ selectedMerchants.length }})
            </el-button>
          </div>
        </div>
        
        <div class="table-container">
          <el-table 
            :data="merchants" 
            v-loading="loading"
            @selection-change="handleMerchantSelectionChange"
            stripe
            class="admin-table"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="merchantId" label="ID" width="80" />
            <el-table-column prop="merchantName" label="商家名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="username" label="用户名" min-width="100" show-overflow-tooltip />
            <el-table-column prop="contactPhone" label="联系电话" min-width="120" />
            <el-table-column prop="merchantAddress" label="地址" min-width="180" show-overflow-tooltip />
            <el-table-column prop="registerTime" label="注册时间" min-width="160">
              <template #default="scope">
                {{ formatDate(scope.row.registerTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="isApproved" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getApprovalStatusType(scope.row.isApproved)">
                  {{ getApprovalStatusText(scope.row.isApproved) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="380" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewMerchant(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="editMerchant(scope.row)">编辑</el-button>
                <el-button 
                  v-if="scope.row.isApproved === 0"
                  size="small" 
                  type="success" 
                  @click="approveMerchant(scope.row.merchantId, 1)"
                >
                  通过
                </el-button>
                <el-button 
                  v-if="scope.row.isApproved === 0"
                  size="small" 
                  type="warning" 
                  @click="approveMerchant(scope.row.merchantId, 2)"
                >
                  拒绝
                </el-button>
                <el-button size="small" type="danger" @click="deleteMerchant(scope.row.merchantId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <CustomPagination
            v-model:current-page="merchantPagination.page"
            v-model:page-size="merchantPagination.size"
            :total="merchantPagination.total"
            :page-sizes="[20, 50, 100]"
            @size-change="handleMerchantPageSizeChange"
            @current-change="handleMerchantPageChange"
          />
        </div>
      </div>

      <!-- 分类管理 -->
      <div v-if="activeMenu === 'categories'" class="content-section">
        <div class="section-header">
          <h2>分类管理</h2>
          <div class="section-actions">
            <el-input
              v-model="categorySearch"
              placeholder="搜索分类名称..."
              prefix-icon="Search"
              style="width: 250px; margin-right: 12px;"
              clearable
              @input="handleCategorySearch"
            />
            <el-button type="primary" @click="showAddCategoryDialog">
              <el-icon><Plus /></el-icon>
              添加分类
            </el-button>
            <el-button type="danger" @click="batchDeleteCategories" :disabled="selectedCategories.length === 0">
              批量删除 ({{ selectedCategories.length }})
            </el-button>
            <el-button type="info" @click="refreshCategories">刷新</el-button>
          </div>
        </div>
        
        <div class="table-container">
          <el-table 
            :data="categories" 
            v-loading="loading"
            @selection-change="handleCategorySelectionChange"
            stripe
            class="admin-table"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="categoryId" label="ID" width="80" />
            <el-table-column prop="categoryName" label="分类名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="categoryEmoji" label="图标" width="80" align="center">
              <template #default="scope">
                <span class="category-emoji">{{ scope.row.categoryEmoji || '🍽️' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="categoryDescription" label="描述" min-width="180" show-overflow-tooltip />
            <el-table-column prop="parentCategoryId" label="父分类" width="100" align="center">
              <template #default="scope">
                <span v-if="scope.row.parentCategoryId">{{ scope.row.parentCategoryId }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" min-width="160">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240" fixed="right">
              <template #default="scope">
                <el-button type="primary" size="small" @click="viewCategoryDetail(scope.row)">
                  详情
                </el-button>
                <el-button type="warning" size="small" @click="editCategory(scope.row)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="deleteCategory(scope.row.categoryId)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <CustomPagination
            v-model:current-page="categoryPagination.page"
            v-model:page-size="categoryPagination.size"
            :total="categoryPagination.total"
            :page-sizes="[20, 50, 100]"
            @size-change="handleCategoryPageSizeChange"
            @current-change="handleCategoryPageChange"
          />
        </div>
      </div>
    </template>
  </DashboardLayout>

  <!-- 用户详情对话框 -->
  <el-dialog v-model="userDetailVisible" title="用户详情" width="600px">
    <div v-if="currentUser" class="user-detail">
      <div class="detail-item">
        <span class="label">用户ID:</span>
        <span>{{ currentUser.userId }}</span>
      </div>
      <div class="detail-item">
        <span class="label">用户名:</span>
        <span>{{ currentUser.username }}</span>
      </div>
      <div class="detail-item">
        <span class="label">头像:</span>
        <el-avatar :size="60" src="/toux.png" />
      </div>
      <div class="detail-item">
        <span class="label">注册时间:</span>
        <span>{{ formatDate(currentUser.registerTime) }}</span>
      </div>
      <div class="detail-item">
        <span class="label">最后登录:</span>
        <span>{{ formatDate(currentUser.lastLoginTime) }}</span>
      </div>
    </div>
  </el-dialog>

  <!-- 用户表单对话框 -->
  <el-dialog 
    v-model="userFormVisible" 
    :title="isEditMode ? '编辑用户' : '添加用户'" 
    width="500px"
    @close="resetUserForm"
  >
    <el-form 
      :model="userForm" 
      :rules="userFormRules" 
      ref="userFormRef" 
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item v-if="!isEditMode" label="密码" prop="password">
        <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item v-if="isEditMode" label="修改密码">
        <el-checkbox v-model="userForm.changePassword">修改密码</el-checkbox>
      </el-form-item>
      <el-form-item v-if="isEditMode && userForm.changePassword" label="新密码" prop="password">
        <el-input v-model="userForm.password" type="password" placeholder="请输入新密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUserForm" :loading="submitting">
          {{ isEditMode ? '更新' : '添加' }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 重置密码对话框 -->
  <el-dialog v-model="resetPasswordVisible" title="重置密码" width="500px">
    <div v-if="currentUser" class="reset-info">
      <p>正在为用户 <strong>{{ currentUser.username }}</strong> 重置密码</p>
    </div>
    <el-form 
      :model="resetPasswordForm" 
      :rules="resetPasswordRules" 
      ref="resetPasswordFormRef" 
      label-width="100px"
    >
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetPasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResetPassword" :loading="submitting">重置密码</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 商家详情对话框 -->
  <el-dialog v-model="merchantDetailVisible" title="商家详情" width="800px">
    <div v-if="currentMerchant" class="merchant-detail">
      <div class="detail-row">
        <div class="detail-item">
          <span class="label">商家ID:</span>
          <span>{{ currentMerchant.merchantId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">用户名:</span>
          <span>{{ currentMerchant.username }}</span>
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-item">
          <span class="label">商家名称:</span>
          <span>{{ currentMerchant.merchantName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">联系电话:</span>
          <span>{{ currentMerchant.contactPhone }}</span>
        </div>
      </div>
      <div class="detail-item full-width">
        <span class="label">商家地址:</span>
        <span>{{ currentMerchant.merchantAddress }}</span>
      </div>
      <div class="detail-item full-width">
        <span class="label">商家描述:</span>
        <span>{{ currentMerchant.merchantDescription || '暂无描述' }}</span>
      </div>
      <div class="detail-row">
        <div class="detail-item">
          <span class="label">营业时间:</span>
          <span>{{ currentMerchant.businessHours || '9:00-22:00' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">审核状态:</span>
          <el-tag :type="getApprovalStatusType(currentMerchant.isApproved)">
            {{ getApprovalStatusText(currentMerchant.isApproved) }}
          </el-tag>
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-item">
          <span class="label">注册时间:</span>
          <span>{{ formatDate(currentMerchant.registerTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">最后登录:</span>
          <span>{{ formatDate(currentMerchant.lastLoginTime) }}</span>
        </div>
      </div>
    </div>
  </el-dialog>

  <!-- 商家表单对话框 -->
  <el-dialog 
    v-model="merchantFormVisible" 
    :title="isMerchantEditMode ? '编辑商家' : '添加商家'" 
    width="600px"
    @close="resetMerchantForm"
  >
    <el-form 
      :model="merchantForm" 
      :rules="merchantFormRules" 
      ref="merchantFormRef" 
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="merchantForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item v-if="!isMerchantEditMode" label="密码" prop="password">
        <el-input v-model="merchantForm.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item v-if="isMerchantEditMode" label="修改密码">
        <el-checkbox v-model="merchantForm.changePassword">修改密码</el-checkbox>
      </el-form-item>
      <el-form-item v-if="isMerchantEditMode && merchantForm.changePassword" label="新密码" prop="password">
        <el-input v-model="merchantForm.password" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="商家名称" prop="merchantName">
        <el-input v-model="merchantForm.merchantName" placeholder="请输入商家名称" />
      </el-form-item>
      <el-form-item label="商家地址" prop="merchantAddress">
        <el-input v-model="merchantForm.merchantAddress" placeholder="请输入商家地址" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="merchantForm.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="商家描述">
        <el-input v-model="merchantForm.merchantDescription" type="textarea" :rows="3" placeholder="请输入商家描述" />
      </el-form-item>
      <el-form-item label="营业时间">
        <el-input v-model="merchantForm.businessHours" placeholder="例如：9:00-22:00" />
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="merchantForm.isApproved" placeholder="请选择审核状态">
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="merchantFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitMerchantForm" :loading="submitting">
          {{ isMerchantEditMode ? '更新' : '添加' }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 分类详情对话框 -->
  <el-dialog v-model="categoryDetailVisible" title="分类详情" width="600px">
    <div v-if="currentCategory" class="category-detail">
      <div class="detail-item">
        <span class="label">分类ID:</span>
        <span>{{ currentCategory.categoryId }}</span>
      </div>
      <div class="detail-item">
        <span class="label">分类名称:</span>
        <span>{{ currentCategory.categoryName }}</span>
      </div>
      <div class="detail-item">
        <span class="label">分类图标:</span>
        <span class="category-emoji">{{ currentCategory.categoryEmoji || '🍽️' }}</span>
      </div>
      <div class="detail-item full-width">
        <span class="label">分类描述:</span>
        <span>{{ currentCategory.categoryDescription || '暂无描述' }}</span>
      </div>
      <div class="detail-item">
        <span class="label">父分类ID:</span>
        <span>{{ currentCategory.parentCategoryId || '无' }}</span>
      </div>
      <div class="detail-item">
        <span class="label">创建时间:</span>
        <span>{{ formatDate(currentCategory.createTime) }}</span>
      </div>
    </div>
  </el-dialog>

  <!-- 分类表单对话框 -->
  <el-dialog 
    v-model="categoryFormVisible" 
    :title="isCategoryEditMode ? '编辑分类' : '添加分类'" 
    width="500px"
    @close="resetCategoryForm"
  >
    <el-form 
      :model="categoryForm" 
      :rules="categoryFormRules" 
      ref="categoryFormRef" 
      label-width="100px"
    >
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="分类图标">
        <el-input v-model="categoryForm.categoryEmoji" placeholder="请输入emoji图标，如：🍕" />
        <div v-if="categoryForm.categoryEmoji" class="emoji-preview">
          <span class="category-emoji">{{ categoryForm.categoryEmoji }}</span>
        </div>
      </el-form-item>
      <el-form-item label="父分类ID">
        <el-input-number v-model="categoryForm.parentCategoryId" :min="0" placeholder="可选，留空表示顶级分类" />
      </el-form-item>
      <el-form-item label="分类描述" prop="categoryDescription">
        <el-input v-model="categoryForm.categoryDescription" type="textarea" :rows="3" placeholder="请输入分类描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="categoryFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCategoryForm" :loading="submitting">
          {{ isCategoryEditMode ? '更新' : '添加' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { 
  DataAnalysis, User, Shop, Grid, Food, ArrowDown, SwitchButton, Search, UserFilled, Plus, WarningFilled, Clock
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DashboardLayout from '@/components/DashboardLayout.vue'
import CustomPagination from '@/components/CustomPagination.vue'

export default {
  name: 'AdminDashboard',
  components: {
    DataAnalysis, User, Shop, Grid, Food, ArrowDown, SwitchButton, Search, UserFilled, Plus, WarningFilled, Clock, DashboardLayout, CustomPagination
  },
  data() {
    return {
      loading: false,
      submitting: false,
      activeMenu: 'overview',
      userSearch: '',
      merchantSearch: '',
      merchantFilter: '',
      categorySearch: '',
      selectedUsers: [],
      selectedMerchants: [],
      selectedCategories: [],
      stats: {
        totalUsers: 0,
        totalMerchants: 0,
        totalFoods: 0
      },
      pendingMerchants: 0,
      users: [],
      merchants: [],
      categories: [],
      userPagination: {
        page: 1,
        size: 20,
        total: 0
      },
      merchantPagination: {
        page: 1,
        size: 20,
        total: 0
      },
      categoryPagination: {
        page: 1,
        size: 20,
        total: 0
      },
      // 用户相关对话框
      userDetailVisible: false,
      userFormVisible: false,
      resetPasswordVisible: false,
      isEditMode: false,
      currentUser: null,
      // 商家相关对话框
      merchantDetailVisible: false,
      merchantFormVisible: false,
      isMerchantEditMode: false,
      currentMerchant: null,
      // 分类相关对话框
      categoryDetailVisible: false,
      categoryFormVisible: false,
      isCategoryEditMode: false,
      currentCategory: null,
      userForm: {
        userId: null,
        username: '',
        password: '',
        avatarPath: '/businessmen.png',
        changePassword: false
      },
      resetPasswordForm: {
        newPassword: '',
        confirmPassword: ''
      },
      merchantForm: {
        merchantId: null,
        username: '',
        password: '',
        merchantName: '',
        merchantAddress: '',
        contactPhone: '',
        merchantDescription: '',
        businessHours: '9:00-22:00',
        avatarPath: '/businessmen.png',
        coverImagePath: '/businessmen.png',
        features: '',
        isApproved: 0,
        changePassword: false
      },
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码至少6个字符', trigger: 'blur' }
        ]
      },
      resetPasswordRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码至少6个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value !== this.resetPasswordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            }, 
            trigger: 'blur' 
          }
        ]
      },
      merchantFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码至少6个字符', trigger: 'blur' }
        ],
        merchantName: [
          { required: true, message: '请输入商家名称', trigger: 'blur' },
          { min: 2, max: 50, message: '商家名称长度为2-50个字符', trigger: 'blur' }
        ],
        merchantAddress: [
          { required: true, message: '请输入商家地址', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { max: 20, message: '电话号码不能超过20位', trigger: 'blur' }
        ]
      },
      categoryForm: {
        categoryId: null,
        categoryName: '',
        categoryEmoji: '',
        parentCategoryId: null,
        categoryDescription: '',
        categoryIconPath: ''
      },
      categoryFormRules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '分类名称长度为2-20个字符', trigger: 'blur' }
        ],
        categoryDescription: [
          { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    
  },
  mounted() {
    this.loadData()
  },
  methods: {
    getCurrentTitle() {
      const titles = {
        overview: '系统概览',
        users: '用户管理',
        merchants: '商家管理',
        categories: '分类管理'
      }
      return titles[this.activeMenu] || '概览'
    },
    
    handleMenuSelect(index) {
      this.activeMenu = index
    },
    
    handleLogout() {
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
      localStorage.removeItem('username')
      localStorage.removeItem('userId')
      localStorage.removeItem('adminId')
      localStorage.removeItem('merchantId')
      
      this.$router.push('/')
      ElMessage.success('退出登录成功')
    },

    async loadData() {
      await this.loadStats()
      await this.loadUsers()
      await this.loadMerchants()
      await this.loadCategories()
    },

    async loadStats() {
      try {
        // 获取统计数据
        const [usersRes, merchantsRes, foodsRes] = await Promise.all([
          fetch('http://localhost:2077/api/admin/stats/users', {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
          }),
          fetch('http://localhost:2077/api/admin/stats/merchants', {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
          }),
          fetch('http://localhost:2077/api/admin/stats/foods', {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
          })
        ])

        if (usersRes.ok) {
          const usersData = await usersRes.json()
          this.stats.totalUsers = usersData.data || 0
        }

        if (merchantsRes.ok) {
          const merchantsData = await merchantsRes.json()
          this.stats.totalMerchants = merchantsData.data || 0
        }

        if (foodsRes.ok) {
          const foodsData = await foodsRes.json()
          this.stats.totalFoods = foodsData.data || 0
        }

        // 获取待审核商家数量
        const pendingRes = await fetch('http://localhost:2077/api/admin/merchants?page=1&size=1&approvalStatus=0', {
          headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        })
        
        if (pendingRes.ok) {
          const pendingData = await pendingRes.json()
          if (pendingData.success) {
            this.pendingMerchants = pendingData.data?.total || 0
          }
        }

      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },

    async loadUsers() {
      this.loading = true
      try {
        const response = await fetch(
          `http://localhost:2077/api/admin/users?page=${this.userPagination.page}&size=${this.userPagination.size}&search=${this.userSearch}`,
          {
            headers: { 
              'Authorization': `Bearer ${localStorage.getItem('token')}`,
              'Content-Type': 'application/json'
            }
          }
        )
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.users = data.data.data
            this.userPagination.total = data.data.total
          } else {
            ElMessage.error(data.message || '加载用户数据失败')
          }
        } else {
          ElMessage.error('网络请求失败')
        }
      } catch (error) {
        console.error('加载用户数据失败:', error)
        ElMessage.error('加载用户数据失败')
      } finally {
        this.loading = false
      }
    },

    async loadMerchants() {
      this.loading = true
      try {
        let url = `http://localhost:2077/api/admin/merchants?page=${this.merchantPagination.page}&size=${this.merchantPagination.size}&search=${this.merchantSearch}`
        
        // 如果有筛选条件，添加到URL中
        if (this.merchantFilter !== null && this.merchantFilter !== '') {
          url += `&approvalStatus=${this.merchantFilter}`
        }
        
        const response = await fetch(url, {
          headers: { 
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.merchants = data.data.data
            this.merchantPagination.total = data.data.total
            
            // 更新待审核商家数量
            this.updatePendingCount()
          } else {
            ElMessage.error(data.message || '加载商家数据失败')
          }
        } else {
          ElMessage.error('网络请求失败')
        }
      } catch (error) {
        console.error('加载商家数据失败:', error)
        ElMessage.error('加载商家数据失败')
      } finally {
        this.loading = false
      }
    },

    async updatePendingCount() {
      try {
        const pendingRes = await fetch('http://localhost:2077/api/admin/merchants?page=1&size=1&approvalStatus=0', {
          headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        })
        
        if (pendingRes.ok) {
          const pendingData = await pendingRes.json()
          if (pendingData.success) {
            this.pendingMerchants = pendingData.data?.total || 0
          }
        }
      } catch (error) {
        console.error('更新待审核数量失败:', error)
      }
    },

    handleMenuSelect(index) {
      this.activeMenu = index
    },

    handleDropdownCommand(command) {
      if (command === 'logout') {
      this.logout()
      }
    },

    logout() {
      ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('token')
        localStorage.removeItem('userRole')
        localStorage.removeItem('username')
        localStorage.removeItem('userId')
        localStorage.removeItem('adminId')
        localStorage.removeItem('merchantId')
        
        // 触发全局状态更新
        window.dispatchEvent(new Event('storage'))
        
        this.$router.push('/login')
        ElMessage.success('退出登录成功')
      }).catch(() => {
        // 用户取消退出
      })
    },

    getMenuTitle(menu) {
      const titles = {
        overview: '系统概览',
        users: '用户管理',
        merchants: '商家管理',
        categories: '分类管理'
      }
      return titles[menu] || '未知'
    },

    getApprovalStatusType(status) {
      const types = { 0: 'warning', 1: 'success', 2: 'danger' }
      return types[status] || 'info'
    },

    getApprovalStatusText(status) {
      const texts = { 0: '待审核', 1: '已通过', 2: '已拒绝' }
      return texts[status] || '未知'
    },

    formatDate(dateString) {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    },

    refreshUsers() {
      this.loadUsers()
    },

    refreshMerchants() {
      this.loadMerchants()
    },

    // 用户管理相关方法
    handleUserSearch() {
      this.userPagination.page = 1
      this.loadUsers()
    },

    handleUserPageChange(page) {
      this.userPagination.page = page
      this.loadUsers()
    },

    handleUserPageSizeChange(size) {
      this.userPagination.size = size
      this.userPagination.page = 1
      this.loadUsers()
    },

    handleUserSelectionChange(selection) {
      this.selectedUsers = selection
    },

    viewUser(user) {
      this.currentUser = user
      this.userDetailVisible = true
    },

    showAddUserDialog() {
      this.isEditMode = false
      this.resetUserForm()
      this.userFormVisible = true
    },

    editUser(user) {
      this.isEditMode = true
      this.currentUser = user
      this.userForm = {
        userId: user.userId,
        username: user.username,
        password: '',
        avatarPath: user.avatarPath,
        changePassword: false
      }
      this.userFormVisible = true
    },

    resetUserForm() {
      this.userForm = {
        userId: null,
        username: '',
        password: '',
        avatarPath: '/businessmen.png',
        changePassword: false
      }
      if (this.$refs.userFormRef) {
        this.$refs.userFormRef.clearValidate()
      }
    },

    async submitUserForm() {
      try {
        await this.$refs.userFormRef.validate()
        this.submitting = true

        const url = this.isEditMode 
          ? `http://localhost:2077/api/admin/users/${this.userForm.userId}`
          : 'http://localhost:2077/api/admin/users'
        
        const method = this.isEditMode ? 'PUT' : 'POST'
        
        const requestData = {
          username: this.userForm.username,
          avatarPath: this.userForm.avatarPath
        }
        
        // 只在需要修改密码时发送密码
        if (!this.isEditMode || this.userForm.changePassword) {
          requestData.password = this.userForm.password
        }

        const response = await fetch(url, {
          method: method,
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success(this.isEditMode ? '用户更新成功' : '用户添加成功')
          this.userFormVisible = false
          this.loadUsers()
        } else {
          ElMessage.error(data.message || '操作失败')
        }
      } catch (error) {
        console.error('提交用户表单失败:', error)
        ElMessage.error('操作失败')
      } finally {
        this.submitting = false
      }
    },

    async deleteUser(userId) {
      try {
        await ElMessageBox.confirm('确定要删除该用户吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        })
        
        const response = await fetch(`http://localhost:2077/api/admin/users/${userId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
        ElMessage.success('删除成功')
        this.loadUsers()
        } else {
          ElMessage.error(data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
          ElMessage.error('删除失败')
        }
      }
    },

    async batchDeleteUsers() {
      if (this.selectedUsers.length === 0) {
        ElMessage.warning('请选择要删除的用户')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${this.selectedUsers.length} 个用户吗？`, 
          '批量删除', 
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const userIds = this.selectedUsers.map(user => user.userId)
        
        const response = await fetch('http://localhost:2077/api/admin/users/batch', {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ userIds })
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success('批量删除成功')
          this.selectedUsers = []
          this.loadUsers()
        } else {
          ElMessage.error(data.message || '批量删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    },

    resetUserPassword(user) {
      this.currentUser = user
      this.resetPasswordForm = {
        newPassword: '',
        confirmPassword: ''
      }
      this.resetPasswordVisible = true
    },

    async submitResetPassword() {
      try {
        await this.$refs.resetPasswordFormRef.validate()
        this.submitting = true

        const response = await fetch(`http://localhost:2077/api/admin/users/${this.currentUser.userId}/reset-password`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ newPassword: this.resetPasswordForm.newPassword })
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success('密码重置成功')
          this.resetPasswordVisible = false
        } else {
          ElMessage.error(data.message || '密码重置失败')
        }
      } catch (error) {
        console.error('密码重置失败:', error)
        ElMessage.error('密码重置失败')
      } finally {
        this.submitting = false
      }
    },

    // 商家管理相关方法
    handleMerchantSearch() {
      this.merchantPagination.page = 1
      this.loadMerchants()
    },

    handleMerchantFilterChange() {
      this.merchantPagination.page = 1
      this.loadMerchants()
    },

    handleMerchantPageChange(page) {
      this.merchantPagination.page = page
      this.loadMerchants()
    },

    handleMerchantPageSizeChange(size) {
      this.merchantPagination.size = size
      this.merchantPagination.page = 1
      this.loadMerchants()
    },

    handleMerchantSelectionChange(selection) {
      this.selectedMerchants = selection
    },

    viewMerchant(merchant) {
      this.currentMerchant = merchant
      this.merchantDetailVisible = true
    },

    showAddMerchantDialog() {
      this.isMerchantEditMode = false
      this.resetMerchantForm()
      this.merchantFormVisible = true
    },

    editMerchant(merchant) {
      this.isMerchantEditMode = true
      this.currentMerchant = merchant
      this.merchantForm = {
        merchantId: merchant.merchantId,
        username: merchant.username,
        password: '',
        merchantName: merchant.merchantName,
        merchantAddress: merchant.merchantAddress,
        contactPhone: merchant.contactPhone,
        merchantDescription: merchant.merchantDescription,
        businessHours: merchant.businessHours,
        avatarPath: merchant.avatarPath,
        coverImagePath: merchant.coverImagePath,
        features: merchant.features,
        isApproved: merchant.isApproved,
        changePassword: false
      }
      this.merchantFormVisible = true
    },

    resetMerchantForm() {
      this.merchantForm = {
        merchantId: null,
        username: '',
        password: '',
        merchantName: '',
        merchantAddress: '',
        contactPhone: '',
        merchantDescription: '',
        businessHours: '9:00-22:00',
        avatarPath: '/businessmen.png',
        coverImagePath: '/businessmen.png',
        features: '',
        isApproved: 0,
        changePassword: false
      }
      if (this.$refs.merchantFormRef) {
        this.$refs.merchantFormRef.clearValidate()
      }
    },

    async submitMerchantForm() {
      try {
        await this.$refs.merchantFormRef.validate()
        this.submitting = true

        const url = this.isMerchantEditMode 
          ? `http://localhost:2077/api/admin/merchants/${this.merchantForm.merchantId}`
          : 'http://localhost:2077/api/admin/merchants'
        
        const method = this.isMerchantEditMode ? 'PUT' : 'POST'
        
        const requestData = {
          username: this.merchantForm.username,
          merchantName: this.merchantForm.merchantName,
          merchantAddress: this.merchantForm.merchantAddress,
          contactPhone: this.merchantForm.contactPhone,
          merchantDescription: this.merchantForm.merchantDescription,
          businessHours: this.merchantForm.businessHours,
          avatarPath: this.merchantForm.avatarPath,
          coverImagePath: this.merchantForm.coverImagePath,
          features: this.merchantForm.features,
          isApproved: this.merchantForm.isApproved
        }
        
        // 只在需要修改密码时发送密码
        if (!this.isMerchantEditMode || this.merchantForm.changePassword) {
          requestData.password = this.merchantForm.password
        }

        const response = await fetch(url, {
          method: method,
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success(this.isMerchantEditMode ? '商家更新成功' : '商家添加成功')
          this.merchantFormVisible = false
          this.loadMerchants()
        } else {
          ElMessage.error(data.message || '操作失败')
        }
      } catch (error) {
        console.error('提交商家表单失败:', error)
        ElMessage.error('操作失败')
      } finally {
        this.submitting = false
      }
    },

    async deleteMerchant(merchantId) {
      try {
        await ElMessageBox.confirm('确定要删除该商家吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await fetch(`http://localhost:2077/api/admin/merchants/${merchantId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success('删除成功')
          this.loadMerchants()
        } else {
          ElMessage.error(data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除商家失败:', error)
          ElMessage.error('删除失败')
        }
      }
    },

    async batchDeleteMerchants() {
      if (this.selectedMerchants.length === 0) {
        ElMessage.warning('请选择要删除的商家')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${this.selectedMerchants.length} 个商家吗？`, 
          '批量删除', 
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const merchantIds = this.selectedMerchants.map(merchant => merchant.merchantId)
        
        const response = await fetch('http://localhost:2077/api/admin/merchants/batch', {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ merchantIds })
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success('批量删除成功')
          this.selectedMerchants = []
          this.loadMerchants()
        } else {
          ElMessage.error(data.message || '批量删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    },

    async approveMerchant(merchantId, status) {
      const action = status === 1 ? '通过' : '拒绝'
      try {
        await ElMessageBox.confirm(`确定要${action}该商家申请吗？`, '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await fetch(`http://localhost:2077/api/admin/merchants/${merchantId}/approval`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ isApproved: status })
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
        ElMessage.success(`${action}成功`)
        this.loadMerchants()
        } else {
          ElMessage.error(data.message || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审核商家失败:', error)
          ElMessage.error(`${action}失败`)
        }
      }
    },

    async batchApproveMerchants(status) {
      if (this.selectedMerchants.length === 0) {
        ElMessage.warning('请选择要操作的商家')
        return
      }

      const action = status === 1 ? '通过' : '拒绝'
      try {
        await ElMessageBox.confirm(
          `确定要批量${action}选中的 ${this.selectedMerchants.length} 个商家吗？`, 
          `批量${action}`, 
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const merchantIds = this.selectedMerchants.map(merchant => merchant.merchantId)
        
        const response = await fetch('http://localhost:2077/api/admin/merchants/batch/approval', {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ merchantIds, isApproved: status })
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success(`批量${action}成功`)
          this.selectedMerchants = []
          this.loadMerchants()
        } else {
          ElMessage.error(data.message || `批量${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`批量${action}失败:`, error)
          ElMessage.error(`批量${action}失败`)
        }
      }
    },

    // 分类管理相关方法
    async loadCategories() {
      this.loading = true
      try {
        const response = await fetch('http://localhost:2077/api/admin/categories/page', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            page: this.categoryPagination.page,
            size: this.categoryPagination.size,
            search: this.categorySearch
          })
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.categories = data.data.data
            this.categoryPagination.total = data.data.total
          } else {
            ElMessage.error(data.message || '加载分类数据失败')
          }
        } else {
          ElMessage.error('网络请求失败')
        }
      } catch (error) {
        console.error('加载分类数据失败:', error)
        ElMessage.error('加载分类数据失败')
      } finally {
        this.loading = false
      }
    },

    refreshCategories() {
      this.loadCategories()
    },

    handleCategorySearch() {
      this.categoryPagination.page = 1
      this.loadCategories()
    },

    handleCategoryPageChange(page) {
      this.categoryPagination.page = page
      this.loadCategories()
    },

    handleCategoryPageSizeChange(size) {
      this.categoryPagination.size = size
      this.categoryPagination.page = 1
      this.loadCategories()
    },

    handleCategorySelectionChange(selection) {
      this.selectedCategories = selection
    },

    viewCategoryDetail(category) {
      this.currentCategory = category
      this.categoryDetailVisible = true
    },

    showAddCategoryDialog() {
      this.isCategoryEditMode = false
      this.resetCategoryForm()
      this.categoryFormVisible = true
    },

    editCategory(category) {
      this.isCategoryEditMode = true
      this.currentCategory = category
      this.categoryForm = {
        categoryId: category.categoryId,
        categoryName: category.categoryName,
        categoryEmoji: category.categoryEmoji,
        parentCategoryId: category.parentCategoryId,
        categoryDescription: category.categoryDescription,
        categoryIconPath: category.categoryIconPath
      }
      this.categoryFormVisible = true
    },

    resetCategoryForm() {
      this.categoryForm = {
        categoryId: null,
        categoryName: '',
        categoryEmoji: '',
        parentCategoryId: null,
        categoryDescription: '',
        categoryIconPath: ''
      }
      if (this.$refs.categoryFormRef) {
        this.$refs.categoryFormRef.clearValidate()
      }
    },

    async submitCategoryForm() {
      try {
        await this.$refs.categoryFormRef.validate()
        this.submitting = true

        const url = this.isCategoryEditMode 
          ? `http://localhost:2077/api/admin/categories/${this.categoryForm.categoryId}`
          : 'http://localhost:2077/api/admin/categories'
        
        const method = this.isCategoryEditMode ? 'PUT' : 'POST'
        
        const response = await fetch(url, {
          method: method,
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.categoryForm)
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success(this.isCategoryEditMode ? '分类更新成功' : '分类添加成功')
          this.categoryFormVisible = false
          this.loadCategories()
        } else {
          ElMessage.error(data.message || '操作失败')
        }
      } catch (error) {
        console.error('提交分类表单失败:', error)
        ElMessage.error('操作失败')
      } finally {
        this.submitting = false
      }
    },

    async deleteCategory(categoryId) {
      try {
        await ElMessageBox.confirm('确定要删除该分类吗？删除后相关菜品的分类将被清空。', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await fetch(`http://localhost:2077/api/admin/categories/${categoryId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success('删除成功')
          this.loadCategories()
        } else {
          ElMessage.error(data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分类失败:', error)
          ElMessage.error('删除失败')
        }
      }
    },

    async batchDeleteCategories() {
      if (this.selectedCategories.length === 0) {
        ElMessage.warning('请选择要删除的分类')
        return
      }

      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${this.selectedCategories.length} 个分类吗？`, '批量删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const categoryIds = this.selectedCategories.map(c => c.categoryId)
        
        const response = await fetch('http://localhost:2077/api/admin/categories/batch', {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(categoryIds)
        })

        const data = await response.json()
        
        if (response.ok && data.success) {
          ElMessage.success('批量删除成功')
          this.selectedCategories = []
          this.loadCategories()
        } else {
          ElMessage.error(data.message || '批量删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除分类失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.admin-layout {
  min-height: 100vh;
  background: var(--background-secondary);
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.admin-header {
  background: white;
  padding: 0 var(--spacing-xl);
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid var(--border-light);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-left .logo {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.logo-icon {
  font-size: 2rem;
}

.logo-text {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-primary);
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-right {
  display: flex;
  align-items: center;
}

.admin-dropdown-trigger {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm) var(--spacing-md);
  border-radius: var(--radius-lg);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.admin-dropdown-trigger:hover {
  background: var(--background-secondary);
  border-color: var(--border-light);
}

.admin-icon {
  font-size: 1.5rem;
  color: var(--primary-color);
  padding: var(--spacing-sm);
  border-radius: var(--radius-lg);
  background: rgba(59, 130, 246, 0.1);
}

.admin-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.admin-name {
  font-weight: 600;
  color: var(--text-primary);
  font-size: 0.95rem;
}

.dropdown-arrow {
  font-size: 0.8rem;
  color: var(--text-secondary);
  transition: transform 0.3s ease;
}

.admin-dropdown-trigger:hover .dropdown-arrow {
  transform: rotate(180deg);
}

/* 下拉菜单样式 */
.el-dropdown-menu {
  border: 1px solid var(--border-light) !important;
  box-shadow: var(--shadow-lg) !important;
  border-radius: var(--radius-lg) !important;
}

.el-dropdown-menu__item {
  padding: var(--spacing-md) var(--spacing-lg) !important;
  display: flex !important;
  align-items: center !important;
  gap: var(--spacing-sm) !important;
  font-size: 0.9rem !important;
  transition: all 0.3s ease !important;
}

.el-dropdown-menu__item:hover {
  background: var(--background-secondary) !important;
  color: var(--primary-color) !important;
}

/* 主容器 */
.admin-container {
  display: flex;
  flex: 1;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

/* 侧边栏 */
.admin-sidebar {
  width: 250px;
  background: var(--background-primary);
  border-right: 1px solid var(--border-light);
  overflow-y: auto;
}

.admin-menu {
  border: none !important;
  background: transparent !important;
}

.admin-menu .el-menu-item {
  height: 50px !important;
  line-height: 50px !important;
  margin: 4px 12px !important;
  border-radius: var(--radius-md) !important;
  color: var(--text-secondary) !important;
  transition: all 0.3s ease !important;
}

.admin-menu .el-menu-item:hover {
  background: rgba(59, 130, 246, 0.1) !important;
  color: var(--primary-color) !important;
}

.admin-menu .el-menu-item.is-active {
  background: var(--gradient-primary) !important;
  color: white !important;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3) !important;
}

/* 主内容区 */
.admin-main {
  flex: 1;
  background: var(--background-primary);
  overflow-y: auto;
}

.breadcrumb-container {
  padding: var(--spacing-lg) var(--spacing-lg) 0;
  background: var(--background-primary);
  border-bottom: 1px solid var(--border-light);
}

.content-wrapper {
  padding: var(--spacing-lg);
}

.content-section {
  margin-bottom: var(--spacing-xl);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  padding-bottom: var(--spacing-md);
  border-bottom: 2px solid var(--border-light);
}

.section-header h2 {
  margin: 0;
  color: var(--text-primary);
  font-weight: 700;
  font-size: 1.5rem;
}

.section-header p {
  margin: 4px 0 0 0;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.section-actions {
  display: flex;
  gap: var(--spacing-sm);
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-xl);
}

.stat-card {
  background: var(--background-primary);
  border: 1px solid var(--border-light);
  border-radius: var(--radius-xl);
  padding: var(--spacing-lg);
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: var(--gradient-primary);
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.stat-card.users::before { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-card.merchants::before { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-card.orders::before { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-card.revenue::before { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
}

.stat-card.users .stat-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-card.merchants .stat-icon { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-card.foods .stat-icon { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-card.pending .stat-icon { background: linear-gradient(135deg, #ffa726 0%, #ff7043 100%); }

.stat-content h3 {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: 0.9rem;
  color: var(--text-secondary);
  font-weight: 500;
}

.stat-number {
  font-size: 2rem;
  font-weight: 800;
  margin: var(--spacing-xs) 0;
  color: var(--text-primary);
}

.stat-trend {
  font-size: 0.8rem;
  font-weight: 600;
}

.stat-trend.positive {
  color: var(--success-color);
}

.stat-trend.negative {
  color: var(--danger-color);
}

/* 快速操作 */
.quick-actions {
  margin-top: var(--spacing-xl);
}

.quick-actions h3 {
  margin-bottom: var(--spacing-lg);
  color: var(--text-primary);
  font-weight: 600;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--spacing-md);
  max-width: 500px;
}

.action-card {
  background: var(--background-primary);
  border: 2px solid var(--border-light);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.action-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: var(--gradient-primary);
  transition: left 0.5s;
  opacity: 0.1;
}

.action-card:hover::before {
  left: 100%;
}

.action-card:hover {
  border-color: var(--primary-color);
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.action-card .el-icon {
  font-size: 2rem;
  color: var(--primary-color);
  margin-bottom: var(--spacing-sm);
}

.action-card span {
  display: block;
  color: var(--text-primary);
  font-weight: 500;
}

.action-badge {
  position: absolute;
  top: 8px;
  right: 8px;
}

/* 表格容器 */
.table-container {
  background: var(--background-primary);
  border-radius: var(--radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  width: 100%;
}

.admin-table {
  width: 100% !important;
}

.admin-table .el-table__cell {
  white-space: nowrap !important;
}

/* 操作列按钮样式 */
.admin-table .el-table__cell .el-button {
  margin-right: 4px;
  margin-bottom: 2px;
}

.admin-table .el-table__cell .el-button:last-child {
  margin-right: 0;
}

.table-container .el-table {
  border-radius: var(--radius-lg) !important;
}

.table-container .el-table th {
  background: var(--background-accent) !important;
  color: var(--text-primary) !important;
  font-weight: 600 !important;
  border-bottom: 1px solid var(--border-light) !important;
}

.table-container .el-table td {
  border-bottom: 1px solid var(--border-light) !important;
}

.table-container .el-table tr:hover td {
  background: rgba(59, 130, 246, 0.05) !important;
}

/* 占位内容 */
.placeholder-content {
  text-align: center;
  padding: var(--spacing-xl);
  background: var(--background-primary);
  border-radius: var(--radius-lg);
  border: 2px dashed var(--border-light);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .admin-container {
    flex-direction: column;
  }
  
  .admin-sidebar {
    width: 100%;
    order: 2;
  }
  
  .admin-main {
    order: 1;
  }
  
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .admin-header {
    padding: 0 var(--spacing-md);
  }
  
  .header-left .logo {
    font-size: 1.3rem;
  }
  
  .admin-name {
    display: none;
  }
  
  .content-wrapper {
    padding: var(--spacing-md);
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-sm);
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .action-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 576px) {
  .action-grid {
    grid-template-columns: 1fr;
  }
}

/* 分页控制 */
.pagination-controls {
  padding: var(--spacing-md) 0;
  display: flex;
  align-items: center;
  font-size: 0.9rem;
  color: var(--text-secondary);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: var(--spacing-lg);
  padding: var(--spacing-md) 0;
}

/* 用户详情 */
.user-detail {
  padding: var(--spacing-md);
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: var(--spacing-md);
  padding: var(--spacing-sm) 0;
  border-bottom: 1px solid var(--border-light);
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item .label {
  font-weight: 600;
  color: var(--text-primary);
  width: 100px;
  margin-right: var(--spacing-md);
}

/* 商家详情 */
.merchant-detail {
  padding: var(--spacing-md);
}

.merchant-detail .detail-row {
  display: flex;
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-md);
}

.merchant-detail .detail-item {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--background-secondary);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-light);
  flex: 1;
}

.merchant-detail .detail-item.full-width {
  flex: none;
  width: 100%;
  margin-bottom: var(--spacing-md);
}

.merchant-detail .label {
  font-weight: 600;
  color: var(--text-primary);
  min-width: 100px;
  margin-right: var(--spacing-md);
  white-space: nowrap;
}

.merchant-detail .detail-item span:last-child {
  color: var(--text-secondary);
}

/* 重置密码 */
.reset-info {
  padding: var(--spacing-md);
  background: var(--background-secondary);
  border-radius: var(--radius-md);
  margin-bottom: var(--spacing-md);
}

.reset-info p {
  margin: 0;
  color: var(--text-secondary);
}

.reset-info strong {
  color: var(--primary-color);
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-sm);
}

/* 表单样式增强 */
.el-form-item__label {
  font-weight: 600 !important;
}

/* 分类管理样式 */
.category-detail {
  padding: var(--spacing-md);
}

.category-detail .detail-item {
  display: flex;
  align-items: center;
  margin-bottom: var(--spacing-md);
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--background-secondary);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-light);
}

.category-detail .detail-item.full-width {
  flex: none;
  width: 100%;
}

.category-detail .label {
  font-weight: 600;
  color: var(--text-primary);
  min-width: 100px;
  margin-right: var(--spacing-md);
  white-space: nowrap;
}

.category-detail .detail-item span:last-child {
  color: var(--text-secondary);
}

.emoji-preview {
  margin-top: var(--spacing-sm);
  text-align: center;
  padding: var(--spacing-md);
  background: var(--background-secondary);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-light);
}

.category-emoji {
  font-size: 1.5rem;
  display: inline-block;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-container {
    flex-direction: column;
  }
  
  .admin-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid var(--border-light);
  }
  
  .section-actions {
    flex-direction: column;
    gap: var(--spacing-sm);
  }
  
  .section-actions > * {
    width: 100%;
  }
  
  .pagination-controls {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-sm);
  }
}
</style> 